2023/12/231563字符
接口
- 接口 与 类型别名 一样,不出现在编译结果中
接口约束对象
interface User {
name: string,
readonly age: number, // readonly 只读修饰符,不可改写
sayHello (): void
}
const user: User = {
name: 'bozai',
age: 18,
sayHello () {}
}
接口约束函数
// type Condition = (n: number) => boolean;
interface Condition { // { 定界符
(n: number): boolean
};
/**
* 求一个数组内符合自定义条件的每一项之和
* @param arr 要进行计算的数组
* @param callBack 回调函数
*/
function sum (arr: number[], callBack: Condition) {
let num = 0;
arr.forEach(val => {
if (callBack(val)) { // 看数组的每一项是否符合自定义的函数条件
num += val;
}
})
return num;
}
let num = sum([1, 2, 3], n => n % 2 !== 0);
console.log(num);
接口的继承
interface A {name: string}
interface B {age: number}
interface C extends A, B {sex: 'boy' | 'girl'}
let obj: C = {
name: 'bozai',
age: 18,
sex: 'boy'
}
类型检查
interface Duck {
sound: 'gagaga',
swin (): void
}
let person = {
name: 'oldwang',
age: 18,
sound: 'gagaga' as 'gagaga', // 类型断言
swin () {
return this.name + '正在游泳,并在' + this.sound + '的叫';
}
}
let duck: Duck = person;
console.log(duck.swin()); //--> oldwang正在游泳,并在gagaga的叫